﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using InhollandAir.auxiliary;

namespace InhollandAir
{
    public class Miles
    {
        public const int DefaultBalance = 0;
        public const int MinimumBalance = 0;
        public const int NegativeTransactionLimit = -2000;
        public const int PositiveTransactionLimit = 2000;
        public const string TransactionLimitStr = "2000";

        private int _id;
        private int _mBalance;
        private int _mLastTransaction;
        private int _mNewTransaction;

        public Miles GetMiles(int id)
        {
            int[] balance = Sql.GetMilesById(id);

            var miles = new Miles
            {
                _id = id,
                Balance = balance[0], //Get balance by user id
                LastTransaction = balance[1], //Get last transaction by user id
                NewTransaction = 0 //Set new transaction to 0 (no change since we only try to GET the Miles)
            };

            Logging.LogEvent(_id, HttpContext.Current.Request.Url, "Miles balanced loaded", "Current balance: " + Balance, false);
            return miles;
        }

        public Miles SetMiles(int transactionSize)
        {
            var miles = new Miles
            {
                _id = _id,
                Balance = Balance + transactionSize,
                LastTransaction = transactionSize,
                NewTransaction = transactionSize
            };

            Logging.LogEvent(_id, HttpContext.Current.Request.Url, "Miles balanced changed", "New balance: " + Balance, false);
            return miles;
        }

        public int Balance
        {
            get { return _mBalance; }
            set { if (value < MinimumBalance) throw new Exception("Balance cannot be lower than 0."); _mBalance = value; }
        }

        public int LastTransaction
        {
            get { return _mLastTransaction; }
            set
            {
                if (value < NegativeTransactionLimit || value > PositiveTransactionLimit) 
                    throw new Exception(string.Format("Transaction have a maximum of {0} InhollandAirMiles.", TransactionLimitStr)); 
                _mLastTransaction = value;
            }
        }

        public int NewTransaction
        {
            get { return _mNewTransaction; }
            set
            {
                if (value < NegativeTransactionLimit || value > PositiveTransactionLimit) 
                    throw new Exception(string.Format("Transaction have a maximum of {0} InhollandAirMiles.", TransactionLimitStr)); 
                _mNewTransaction = value;
            }
        }
    }
}